package net.disk;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Account;
import com.dropbox.client2.DropboxAPI.DropboxInputStream;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.RequestTokenPair;
import com.dropbox.client2.session.Session.AccessType;
import com.dropbox.client2.session.WebAuthSession;
import com.dropbox.client2.session.WebAuthSession.WebAuthInfo;

public class DropBoxAccess
{
	private static DropboxAPI<?> api;
	static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
	private final static String TESTS_DIR = "/" + dateFormat.format(new Date());
	private static File foo = new File("testfiles", "foo.txt");
	private static File foo2 = new File("testfiles", "foo2.txt");
	private static File song = new File("testfiles", "dropbox_song.mp3");
	private static File frog = new File("testfiles", "Costa Rican Frog.jpg");
	private static File f123 = new File("123.txt");
	private static File f456 = new File("456.txt");
	private static File f789 = new File("789.txt");
	private static File fuck = new File("/abc.txt");
	private static String APP_KEY = "68kap60q5506wpy";
	private static String APP_SECRET = "xexlkufc2m0gajl";

	public static void main(final String[] args)
	{
		final DropBoxAccess dropbox = new DropBoxAccess();
		System.out.println("markstc");
		dropbox.queryChildren("/");
		final DropboxInputStream in = dropbox.downloadFile("/abc.txt");
		try {
			final byte[] downloaded = Util.streamToBytes(in);
			System.out.println("caitongda :" + new String(downloaded));
		}
		catch (final IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * dropbox.accountInfo(); dropbox.createFolder(TESTS_DIR); dropbox.uploadFile(foo, TESTS_DIR + "/" + foo.getName());
		 * dropbox.moveFile(TESTS_DIR + "/" + foo.getName(), TESTS_DIR + "/" + foo.getName() + "moved");
		 * dropbox.downloadFile(TESTS_DIR + "/" + foo.getName() + "moved", "/home/markcai/Dropbox/Learn/temp.txt");
		 * dropbox.updateFile(foo2, TESTS_DIR + "/" + foo.getName() + "moved");
		 */
	}

	public DropBoxAccess()
	{
		try {
			final AppKeyPair consumerTokenPair = new AppKeyPair(APP_KEY, APP_SECRET);
			final WebAuthSession session = new WebAuthSession(consumerTokenPair, AccessType.APP_FOLDER);
			final WebAuthInfo mywebauthinfo = session.getAuthInfo();
			System.out.println(mywebauthinfo.url);
			System.out.println("Please accept the request:");
			try {
				Runtime.getRuntime().exec("/usr/bin/firefox " + mywebauthinfo.url);
			}
			catch (final IOException e) {
				e.printStackTrace();
			}
			System.out.println("Press enter after authorizing.");
			System.in.read();
			final RequestTokenPair myrequesttokenpair = mywebauthinfo.requestTokenPair;
			session.retrieveWebAccessToken(myrequesttokenpair);
			api = new DropboxAPI<WebAuthSession>(session);
		}
		catch (final Throwable t) {
			t.printStackTrace();
			assert false : "Total failure trying to start WebAuthSession." + t;
		}
	}

	public void accountInfo()
	{
		try {
			final Account info = api.accountInfo();
			System.out.println("country: " + info.country);
			System.out.println("displayName: " + info.displayName);
			System.out.println("quota: " + info.quota);
			System.out.println("quotaNaormal: " + info.quotaNormal);
			System.out.println("regerralLink: " + info.referralLink);
			System.out.println("uid: " + info.uid);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in accountInfo: " + e);
		}
		System.out.println("accountInfo succeed!");
	}

	public boolean checkfile(final Entry e, final File f, final String path)
	{
		if (e.bytes == f.length() && e.isDir == false && e.path.equals(path)) {
			return true;
		}
		else {
			return false;
		}
	}

	public void createFolder(final String path)
	{
		try {
			final Entry ent = api.createFolder(path);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in createFolder: " + e);
		}
		System.out.println("createFolder successed!");
	}

	public void delete(final String path)
	{
		try {
			api.delete(path);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in delete: " + e);
		}
		System.out.println("delete succeed!");
	}

	public DropboxInputStream downloadFile(final String fromPath)
	{
		DropboxInputStream info = null;
		try {
			info = api.getFileStream(fromPath, null);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in downloadFile: " + e);
		}
		System.out.println("downloadfile succeed!");
		return info;
	}

	public void moveFile(final String fromPath, final String toPath)
	{
		try {
			final Entry moveEnt = api.move(fromPath, toPath);
		}
		catch (final DropboxException e) {
			System.out.println("Something went wrong in moveFile: " + e);
		}
		System.out.println("movefile succeed");
	}

	@SuppressWarnings("null")
	public List<String> queryallChildren(final String path)
	{
		final List<String> filelist = new ArrayList<String>();
		try {
			final Entry entries = api.metadata(path, 100, null, true, null);
			for (final Entry e : entries.contents) {
				System.out.println("gogogogo");
				if (true) {
					filelist.add(e.path);
					System.out.println(e.path);
				}
			}
			if (filelist.size() == 0) {
				System.out.println("Can not find!");
			}
		}
		catch (final DropboxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}

	public List<DropboxAPI.Entry> queryChildren(final String path)
	{
		List<DropboxAPI.Entry> filelist = null;
		try {
			filelist = api.search(path, ".", 1000, false);
		}
		catch (final DropboxException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < filelist.size(); i++) {
			System.out.println(filelist.get(i).path);
		}
		if (filelist.size() == 0) {
			System.out.println("Can not find!");
		}
		return filelist;
	}

	public void renameFile(final String fromPath, final String newname)
	{
		try {
			final Entry moveEnt = api.move(fromPath, newname);
		}
		catch (final DropboxException e) {
			System.out.println("Something went wrong in moveFile: " + e);
		}
		System.out.println("movefile succeed");
	}

	public long totalbytes()
	{
		Account info = null;
		try {
			info = api.accountInfo();
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in accountInfo: " + e);
		}
		return info.quota;
	}

	public void updateFile(final File file, final String target)
	{
		try {
			final FileInputStream fis = new FileInputStream(file);
			final Entry newEntry = api.putFileOverwrite(target, fis, file.length(), null);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in uploadFile: " + e);
		}
		System.out.println("updatefile succeed!");
	}

	public void uploadFile(final File file, final String target)
	{
		try {
			final FileInputStream fis = new FileInputStream(file);
			final Entry newEntry = api.putFile(target, fis, file.length(), null, null);
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in uploadFile: " + e);
		}
		System.out.println("uploadfile succeed!");
	}

	public long usedbytes()
	{
		Account info = null;
		try {
			info = api.accountInfo();
		}
		catch (final Exception e) {
			System.out.println("Something went wrong in accountInfo: " + e);
		}
		return info.quotaNormal;
	}
}
